package com.example.petstore.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.IOException;

public class GiteeLogin {

    private static final String client_id = "ba92f844c06bf93080ad7fc1b86468a002305bc1a859e753eaffdf0d712b9351";
    private static final String redirect_uri = "http://localhost:8080/bindPhoneNumber";
    private static final String client_secret = "290b71cf57ecbb4e60b47f34465c98c0ff658910cf58bb1eafb9af7a0316680e";
    private static String getAccessKey(String code) {
        OkHttpClient client = new OkHttpClient();
        // 通过该地址能够获取到access_token
        String url = "https://gitee.com/oauth/token";
        // 封装请求参数
        RequestBody requestBody = new FormBody.Builder()
                .add("grant_type", "authorization_code")
                .add("code", code)
                .add("client_id", client_id)
                .add("redirect_uri", redirect_uri)
                .add("client_secret", client_secret)
                .build();

        Request request = new Request.Builder()
                .post(requestBody)
                .url(url).build();
        String accessKey = "";
        try {
            Response response = client.newCall(request).execute();
            String json = response.body().string();
            System.out.println(json);
            JSONObject jsonObject =  JSON.parseObject(json);
            // 获取json串中的access_token属性
            accessKey= (String) jsonObject.get("access_token");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return accessKey;
    }

    public static String getUserInfo(String code) {
        String json = "";
        OkHttpClient client = new OkHttpClient();
        String accessKey = getAccessKey(code);
        // 通过该地址能够获取到用户信息
        String url = "https://gitee.com/api/v5/user?access_token=" + accessKey;
        Request request = new Request.Builder()
                .get()
                .url(url).build();
        try {
            Response response = client.newCall(request).execute();
            json = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }
}
